package com.tanhua.autoconfig.template;


import com.tanhua.autoconfig.properties.JWTProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.Map;

public class JWTTemplate {
    private JWTProperties jwtProperties;

    public JWTTemplate(JWTProperties properties) {
        this.jwtProperties = properties;
    }

    public String decode(Map<String, Object> map, Long expiration) {
        long now = System.currentTimeMillis();
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, jwtProperties.getKey())
                .setClaims(map)
                .setExpiration(new Date(now + expiration))
                .compact();
    }

    public Object encode(String token, String key) {
        Claims claims = Jwts.parser()
                .setSigningKey(jwtProperties.getKey())
                .parseClaimsJws(token)
                .getBody();
        return claims.get(key);
    }

    public Claims getClaims(String token) {
        return Jwts.parser()
                .setSigningKey(jwtProperties.getKey())
                .parseClaimsJws(token).getBody();
    }
}
